package com.lagou.handler;

import com.lagou.pojo.RpcRequest;
import com.lagou.service.UserServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

public class UserServerHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    ApplicationContext applicationContext;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
//        if(msg.toString().startsWith("UserService")){
//            UserServiceImpl userService = new UserServiceImpl();
//            String result = userService.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
//            ctx.writeAndFlush(result);
//        }
        RpcRequest msgTemp = (RpcRequest) msg;
        if(msgTemp.getMethodName().startsWith("sayHello")){
            UserServiceImpl userService = new UserServiceImpl();
            Object[] parameters =  msgTemp.getParameters();
            String result = userService.sayHello(parameters[0].toString());
            ctx.writeAndFlush(result);
        }

//        if (msg instanceof RpcRequest) {
//            //通过rcp request 反射调用
//            RpcRequest request = ((RpcRequest) msg);
//            //找到其实现类
//            Class clazz = Class.forName(request.getClassName());
//            Object obj = applicationContext.getBean(clazz);
//            Method method = clazz
//                    .getMethod(request.getMethodName(), request.getParameterTypes());
//            Object result = method.invoke(obj, request.getParameters());
//            ctx.writeAndFlush(result);
//        }
    }
}
